const signature = require('../app/lib/signature');

const APP_ID = '2';
const APP_SECRET = '6ee4d8c7a4f42a39c51379f2b00d39ea';

describe('签名测试', () => {
    it('生成签名 GET', () => {
        signature({
            appId: APP_ID,
            appSecret: APP_SECRET,
            query: 'b=2&d=4&a=1',
            method: 'get',
            path: '/templets',
            timestamp: 1480576350
        })
        .should.to.equal('94EAFD426FD7275514207009B5A4EE0C61D955B9');
    });

    it('生成签名 POST', () => {
        signature({
            appId: APP_ID,
            appSecret: APP_SECRET,
            query: 'd=4&a=1',
            method: 'post',
            path: '/templets',
            timestamp: 1480576350,
            body: {
                content: '{"a":1,"b":"😄"}'
            }
        })
        .should.to.equal('27990262D04C578FACA577B0D9C8AAE1811FA2F4');
    });

    it('校验签名', () => {
        const axios = require('axios');

        const timestamp = Math.floor(Date.now() / 1000);
        const params = {
            _: timestamp,
            x: 1
        };
        const uri = '/attributes';

        let sign = signature({
            appId: APP_ID,
            appSecret: APP_SECRET,
            timestamp: timestamp,
            method: 'get',
            query: params,
            path: uri
        });

        return axios.get(`http://api.xsbapp.dev${uri}`, {
            params: params,
            headers: {
                'X-Appid': APP_ID,
                'X-Timestamp': timestamp,
                'X-Signature': sign
            }
        })
        .catch(err => {
            let data = err.response && err.response.data || {};
            let message = data.message || err.message;

            throw new Error(message);
        })
        .should.eventually.to.be.an('object');
    });
});
